from fastapi import APIRouter,Request,Depends,HTTPException
router = APIRouter()
from .model import User
from .v_model import User_data
from tool import db
from sqlalchemy import or_
import jwt

@router.post("/register")
def register(user:User_data):
    print(user,type(user))
    user_data = db.query(User).filter(or_(User.username == user.username, User.email == user.email)).all()
    if user_data:
        return False
    new_user = User(username=user.username, password=user.password,email=user.email)
    db.add(new_user)
    db.commit()
    return True


@router.post("/login")
def read_root():
    encoded = jwt.encode({"username": "liu"}, "secret", algorithm="HS256")    # 登陆生成token
    return {"token": encoded}

def get_username(requst:Request):
    token = requst.headers.get('authorization')
    try:
        res = jwt.decode(token, "secret", algorithms=["HS256"])
    except:
        raise HTTPException(status_code=404, detail="没有登录")    
    return res

@router.get("/test")
def read_item(username: str =Depends(get_username)):        # 依赖注入，验证token
    return username